<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form v-bind="formLayout">
        <a-row :gutter="48">
          <a-col :md="10" :sm="24">
            <a-form-item
              label="状态" >
              <a-radio-group v-model="queryParam.status" button-style="solid" @change="$refs.table.refresh(true)" style="white-space:nowrap;">
                <a-radio-button :value="-1">
                  全部
                </a-radio-button>
                <a-radio-button :value="1">
                  未开始
                </a-radio-button>
                <a-radio-button :value="2">
                  填报中
                </a-radio-button>
                <a-radio-button :value="3">
                  评审中
                </a-radio-button>
                <a-radio-button :value="4">
                  公示中
                </a-radio-button>
                <a-radio-button :value="5">
                  已结束
                </a-radio-button>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="48">
          <a-col :md="10" :sm="24">
            <a-form-item
              label="关键字">
              <a-input v-model="queryParam.name" placeholder="请输入申报体系" @keyup.enter.native="$refs.table.refresh(true)"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button style="margin-left: 8px" @click="setEmpty">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator" v-if="role.roleKey === 'admin'">
      <span style="margin-right: 16px;">已选中{{ selectedRowKeys.length }}行</span>
      <a-button type="primary" icon="plus" @click="handleAdd">新增</a-button>
      <a-button icon="delete" @click="handleDeleteBatch">删除</a-button>
    </div>

    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :rowSelection="rowSelection"
      :customRow="customRow"
      showPagination="auto"
    >
      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>

      <span slot="name" slot-scope="text">
        <span class="systemName"> {{ text }}</span>
      </span>

      <span slot="status" slot-scope="text">
        {{ text | statusFilter }}
      </span>

      <span slot="action" slot-scope="text, record">
        <template v-if="role.roleKey === 'admin'">
          <a @click.stop="handleCheck(record)">查看</a>
          <a-divider type="vertical" />
          <a @click.stop="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click.stop="handleDelete(record)" v-if="!(record.status === 2 || record.status === 3 || record.status === 4)" >删除</a>
        </template>
      </span>
    </s-table>

    <create-form
      ref="createModal"
      :visible="visible"
      :loading="confirmLoading"
      :model="mdl"
      @cancel="handleCancel"
      @ok="handleOk"
    />
    <check-form
      ref="checkModal"
    />
  </a-card>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import { getSystem, saveSystem, deleteSystem } from '@/api/system'

import CreateForm from './CreateForm'
import CheckForm from './CheckForm'

let columnsData = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '申报体系',
    dataIndex: 'name',
    scopedSlots: { customRender: 'name' }
  },
  {
    title: '申报组织数量',
    dataIndex: 'declarationNum'
  },
  {
    title: '状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '250px',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'DeclareSystemList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    CheckForm
  },
  data () {
    this.formLayout = {
      labelAlign: 'left',
      labelCol: {
        span: 4
      },
      wrapperCol: {
        span: 20
      }
    }
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 查询参数
      queryParam: { status: -1 },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        if (requestParameters.status === -1) {
          delete requestParameters.status
        }
        return getSystem(requestParameters)
          .then(res => {
            console.log(res)
            return res
          })
      },
      columns: [],
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  filters: {
    statusFilter (status) {
      const statusMap = {
        1: '未开始',
        2: '填报中',
        3: '评审中',
        4: '公示中',
        5: '已结束'
      }
      return statusMap[status]
    }
  },
  activated () {
    // 切换角色 需要重新执行
    let tempColumns = JSON.parse(JSON.stringify(columnsData))
    if (this.$store.getters.roles.roleKey != 'admin') {
      tempColumns = tempColumns.filter(v => v.dataIndex != 'action')
    }
    this.columns = tempColumns
  },
  deactivated () {
    this.visible = false
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        getCheckboxProps: record => ({
          props: {
            disabled: record.status === 2 || record.status === 3 || record.status === 4
          }
        })
      }
    },
    role () {
      return this.$store.getters.roles
    }
  },
  methods: {
    setEmpty () {
      this.queryParam = { status: -1 }
      this.$refs.table.refresh(true)
    },
    customRow (record) {
      return {
        props: {
        },
        on: { // 事件
            click: (event) => {
              if (
                this.role.roleKey === 'admin' || this.$store.getters.isMzRole ||
                (record.status === 2 && this.role.roleKey === 'GUIDANCE_EXPERT') ||
                (record.status === 3 && this.role.roleKey === 'EXPERT')
                ) {
                this.$router.push({ name: 'DeclareSystemOrg', query: { declarationSystemId: record.id } })
              } else {
                this.$message.warning('当前无权限')
                // this.$router.push({ name: 'DeclareSystemOrg', query: { declarationSystemId: record.id } })
              }
            } // 点击行
          }
        }
    },
    handleDeleteBatch () {
      if (this.selectedRowKeys.length === 0) {
        this.$warning({
          title: '提示',
          content: '请选择需要删除的数据'
        })
      } else {
        console.log(this.selectedRowKeys)
        deleteSystem({
            id: this.selectedRowKeys.join(',')
          }).then(res => {
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('批量删除成功')
            })
      }
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.mdl = { ...record }
      this.visible = true
    },
    handleCheck (record) {
      this.$refs.checkModal.checkView(record)
    },
    handleDelete (record) {
      this.$confirm({
        title: '删除确认',
        content: '确认要删除该数据吗？并且不可恢复！',
        okType: 'danger',
        onOk: () => {
          deleteSystem({
            id: record.id
          }).then(res => {
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.success('删除成功')
            })
        }
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          console.log('values', values)
          saveSystem(values).then(res => {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success(values.id > 0 ? '修改成功' : '新增成功')
            }).finally(() => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>

<style lang="less" scoped>
:deep(.ant-radio-button-wrapper ) {
  margin-right: 8px;
    &:first-child {
      border-radius: 0;
    }
    &:last-child {
      border-radius: 0;
    }
  }
  .systemName {
    &:hover {
      color: #1890ff;
      cursor: pointer;
    }
  }
</style>
